<template>
  <el-card>
    <el-form
      label-width="120"
      ref="dataDom"
      :model="dataForm"
      :rules="dataRules"
    >
      <el-form-item label="SPU名称" prop="spuName">
        <el-input placeholder="spu名称" v-model="dataForm.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌" prop="tmId">
        <el-select placeholder="选择" v-model="dataForm.tmId">
          <el-option
            v-for="obj in brandData"
            :value="obj.id"
            :label="obj.tmName"
            :key="obj.id"
            >{{ obj.tmName }}</el-option
          >
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input
          type="textarea"
          placeholder="SPU描述"
          v-model="dataForm.description"
          rows="4"
        />
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload
          v-model:file-list="dataForm.spuImageList"
          :action="BASE_URL + '/admin/product/upload'"
          list-type="picture-card"
          :before-upload="beforeAvatarUpload"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-exceed="handleUploadExceed"
          :on-success="handleUploadSuccess"
          :limit="3"
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png files with a size less than 500kb
            </div>
          </template>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img
            w-fill
            :src="dialogImageUrl"
            alt="Preview Image"
            class="imageShow"
          />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select :placeholder="selectTip" v-model="salesSelect">
          <el-option
            v-for="obj in salesSelectActive"
            :key="obj.id"
            :label="obj.name"
            :value="`${obj.id}:${obj.name}`"
            >{{ obj.name }}</el-option
          >
        </el-select>
        <el-button type="primary" @click="addSales" :disabled="!salesSelect"
          >添加销售属性</el-button
        >
        <el-table :data="dataForm.spuSaleAttrList" style="width: 100%" border>
          <el-table-column
            fixed
            prop="date"
            label="序号"
            width="80"
            type="index"
          />
          <el-table-column prop="saleAttrName" label="属性名" width="200" />
          <el-table-column
            prop="spuSaleAttrValueList"
            label="属性值名称列表"
            width="800"
          >
            <template v-slot="{ row }">
              <div v-if="!row.isEdit">
                <el-tag
                  v-for="(tag, index) in row.spuSaleAttrValueList"
                  :key="index"
                  class="mr-right"
                  closable
                  :type="tag.type"
                  @close="deleteTag(row, index)"
                  >{{ tag.saleAttrValueName }}</el-tag
                >
                <el-button
                  :icon="Plus"
                  size="small"
                  @click="toggleTag(row)"
                ></el-button>
              </div>
              <el-input
                v-else
                v-model="salesTag"
                @blur="putInSales(row)"
                size="small"
                class="input_tag"
                ref="tagDom"
              />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作">
            <template v-slot="{ $index }">
              <el-button
                type="danger"
                :icon="Delete"
                size="small"
                @click="handleClick($index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="confirm">保存</el-button>
        <el-button type="primary" @click="cancle">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "XSpuAddOrEdit",
};
</script>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { Plus, Delete } from "@element-plus/icons-vue";
import { reqBrandList } from "@/api/product/brand";
import {
  reqAddSpu,
  reqSales,
  reqSpuImageItem,
  reqSpuSalesItem,
  reqSpuUpdateItem,
} from "@/api/product/spu";
import { ElMessage, type UploadProps, type UploadUserFile } from "element-plus";
import { beforeAvatarUpload } from "@/utils/tools";
import type { ArrayTableObj, salesObj } from "@/api/product/model/index";
import type {
  AllSpuType,
  ArraySpuSaleAttrList,
  spuSaleAttrlist,
  spuImageList,
} from "@/api/product/model/spuType";
import { useSpuStore } from "@/stores/spu";
const BASE_URL = import.meta.env.VITE_API_URL;
const spuStore = useSpuStore();
const emit = defineEmits(["toggle"]);
const props = defineProps<{ isEdit: number }>();
const fileList = ref<UploadUserFile[]>([
  // {
  //   name: "food.jpeg",
  //   url: "/admin/product/upload",
  // },
]);

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const dataDom = ref();
const brandData = ref<ArrayTableObj>([]);
const selasData = ref<salesObj[]>([]);
onMounted(async () => {
  const result = await reqBrandList();
  brandData.value = result;
});
onMounted(async () => {
  const result = await reqSales();
  selasData.value = result;
});

const dataForm = reactive<AllSpuType<UploadUserFile>>({
  // category3Id: 0,
  description: "",
  // id: 0,
  spuImageList: [
    // {
    //   id: 0,
    //   imgName: "string",
    //   imgUrl: "string",
    //   spuId: 0,
    // },
  ] as any,
  spuName: "",
  spuSaleAttrList: [
    // {
    //   baseSaleAttrId: 0,
    //   id: 0,
    //   saleAttrName: "string",
    //   spuId: 0,
    //   spuSaleAttrValueList: [
    //     // {
    //     //   baseSaleAttrId: 0,
    //     //   id: 0,
    //     //   isChecked: "string",
    //     //   saleAttrName: "string",
    //     //   saleAttrValueName: "string",
    //     //   spuId: 0,
    //     // },
    //   ],
    // },
  ] as any,
  tmId: undefined,
});
onMounted(async () => {
  if (props.isEdit === 2) {
    const { description, spuName, id } = spuStore.$state.skuInfo;
    dataForm.description = description;
    dataForm.spuName = spuName;
    const images = await reqSpuImageItem(id as number);
    const sales = await reqSpuSalesItem(id as number);
    const imageData = images.map((item) => {
      return { name: item.imgName, url: item.imgUrl };
    });
    dataForm.spuImageList = imageData;
    dataForm.spuSaleAttrList = sales;
    dataForm.tmId = spuStore.$state.skuInfo.tmId;
  }
});
// 自定义校验函数
const spuSaleAttrListValidator = (
  rule: any,
  value: ArraySpuSaleAttrList,
  callback: any
) => {
  /*
    rule 规则信息对象
    value 校验数据的值
    callback 是一个函数，必须要调用
      callback(); 校验通过
      callback(new Error('错误信息')); 校验失败
  */
  // 至少添加一个销售属性
  if (!value.length) {
    callback(new Error("请至少添加一个销售属性"));
    return;
  }
  // 每个销售属性至少添加一个属性值
  if (
    value.some((spuSaleAttr: any) => !spuSaleAttr.spuSaleAttrValueList.length)
  ) {
    callback(new Error("每个销售属性至少添加一个属性值"));
    return;
  }
  // 一定要调用，校验通过
  callback();
};
const dataRules = reactive({
  spuName: [{ required: true, message: "请输入SPU名称", trigger: "blur" }],
  tmId: [{ required: true, message: "请选择SPU品牌", trigger: "change" }],
  description: [{ required: true, message: "请输入SPU描述", trigger: "blur" }],
  spuImageList: [{ required: true, message: "请上传SPU图片" }],
  spuSaleAttrList: [
    {
      required: true,
      validator: spuSaleAttrListValidator,
    },
  ],
});
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url as string;
  dialogVisible.value = true;
};

function cancle() {
  emit("toggle", 0);
}
const handleUploadSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  //选择图片赋值的地址
  // formData.logoUrl = URL.createObjectURL(uploadFile.raw!);
  // console.log(response);
  // (formData.logoUrl = response.data),
  //   // 清空表单校验失败的信息
  //   // dataDom.value.clearValidate(); // 清空所有表单项的校验信息
  //   dataDom.value.clearValidate(["logoUrl"]); // 清空logoUrl表单项的校验信息
  dataDom.value.clearValidate(["spuImageList"]);
};
function handleUploadExceed() {
  ElMessage.error("最多上传3张图片哦!!");
}
async function confirm() {
  try {
    await dataDom.value.validate();
    const category3Id = spuStore.$state.category3Id;
    var imageArr = dataForm.spuImageList.map((item) => {
      const img = item as any;
      if (img.response) {
        return { imgUrl: img.response.data, imgName: img.name };
      } else {
        return { imgUrl: img.url, imgName: img.name };
      }
    });
    const { description, spuName, spuSaleAttrList, tmId, spuImageList } =
      dataForm;
    let spuData: AllSpuType = {
      description,
      spuName,
      spuSaleAttrList,
      tmId,
      spuImageList: imageArr,
      category3Id,
    };
    if (props.isEdit === 2) {
      spuData.id = spuStore.$state.skuInfo.id;
      await reqSpuUpdateItem(spuData);
    } else {
      await reqAddSpu(spuData);
    }
    // console.log("~~", spuData);
    props.isEdit == 1 && ElMessage.success("添加SPU成功!!!");
    props.isEdit == 2 && ElMessage.success("修改SPU成功!!!");
    emit("toggle", 0);
  } catch (error) {
    console.log("校验未通过", error);
  }
}
/*** 销售属性
 * ****/

const salesSelect = ref("");
const salesTag = ref("");
const tagDom = ref();
const salesSelectActive = computed(() => {
  return selasData.value.filter((item) => {
    return !dataForm.spuSaleAttrList.some((element) => {
      return element.baseSaleAttrId === item.id;
    });
  });
});
const selectTip = computed(() => {
  if (salesSelectActive.value.length) {
    return `还有${salesSelectActive.value.length}未选择`;
  } else {
    return "没有啦!";
  }
});
function addSales() {
  const [id, name] = salesSelect.value.split(":");
  dataForm.spuSaleAttrList.push({
    baseSaleAttrId: +id,
    saleAttrName: name,
    spuSaleAttrValueList: [
      // {
      //   baseSaleAttrId: 0,
      //   id: 0,
      //   isChecked: "string",
      //   saleAttrName: "string",
      //   saleAttrValueName: "string",
      //   spuId: 0,
      // },
    ],
    isEdit: false,
  } as any);
  salesSelect.value = "";
}
const handleClick = (index: number) => {
  dataForm.spuSaleAttrList.splice(index, 1);
};
//失去焦点加tag
function putInSales(row: spuSaleAttrlist) {
  if (!salesTag.value) return;
  row.spuSaleAttrValueList.push({
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: salesTag.value,
  });
  row.isEdit = false;
  salesTag.value = "";
}
async function toggleTag(row: spuSaleAttrlist) {
  dataForm.spuSaleAttrList.forEach((element) => {
    element.isEdit = false;
  });
  row.isEdit = true;
  nextTick();
  setTimeout(() => {
    tagDom.value.focus();
  });
}
function deleteTag(row: spuSaleAttrlist, index: number) {
  row.spuSaleAttrValueList.splice(index, 1);
}

// category3Id: 1
// description: "yyyyyyyyyyyyyyyyyyy"
// id: 5013
// spuImageList: (2) [{…}, {…}]
// spuName: "yyyyyyyxxxxxxxxx"
// spuSaleAttrList: Proxy {0: {…}, 1: {…}}
// tmId: 18745
</script>

<style scoped>
.textarea {
  height: 200px;
}
.imageShow {
  width: 100%;
  height: 100%;
}
.input_tag {
  width: 200px;
}
</style>
